const QQMapWX = require('../common/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min')

const app = getApp()

export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

export const dateFormatTime = (fmt, date) => {
  //until.dateFormatTime("YYYY-mm-dd HH:MM:SS",date)
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

export const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//取倒计时（天时分秒）
export const getTimeLeft = (datetimeTo) => {
  // 计算目标与现在时间差（毫秒）new Date(date.replace(/-/g, '/'))
  let time1 = new Date(datetimeTo).getTime();
  let time2 = new Date().getTime();
  let mss = time1 - time2;

  // 将时间差（毫秒）格式为：天时分秒
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);

  return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
}

export const showToast = (title, duration = 2000, mask = false) => {
  return new Promise(function (resolve, reject) {
    wx.showToast({
      title,
      duration,
      mask,
      icon: 'none',
      success: () => resolve(),
      fail: () => reject()
    })
  })
}

export const showLoading = (title = '加载中...', mask = true) => {
  wx.showLoading({ title, mask })
}

/**
 * 计算底部安全距离
 */
export const getSafeArea = () => {
  const system = wx.getSystemInfoSync()
  return system.safeArea && system.safeArea.bottom && system.screenHeight ? system.screenHeight - system.safeArea.bottom : 0;
}

/**
 * 根据地址 打开地图
 */
export const openMmap = (location) => {
  const qqmapsdk = new QQMapWX({ key: app.globalData.qq_maps_key });
  qqmapsdk.geocoder({
    address: location,
    success: (res) => {
      var result = res.result;
      wx.openLocation({
        latitude: result.location.lat,
        longitude: result.location.lng,
        address: location,
        scale: 18
      })
    },
    fail: () => showToast('获取定位失败, 请稍后重试')
  })
}

